package com.talent.talentgateway.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @ClassName：IPLimitFilter
 * @Author: hszhou
 * @Date: 2024/12/6 13:01
 * @Description: 限制同一个ip访问次数频繁
 */
@Component
@Slf4j
public class IPLimitFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest();

        long startTime = System.currentTimeMillis();
        log.info("请求开始，请求路径：{}，请求时间：{}",request.getURI().toString(),startTime);
        ServerHttpResponse response = exchange.getResponse();
        Mono<Void> filter = chain.filter(exchange)
                .doFinally(res->{
                    long endTime = System.currentTimeMillis();
                    log.info("请求结束，请求ip：{}，请求路径：{}，请求方法：{}，响应状态码：{},耗时：{}",
                            request.getRemoteAddress().getHostName(),
                            request.getPath().value(),
                            request.getMethod().name(),
                            response.getStatusCode().value(),
                            endTime-startTime);
                });

        return filter;
    }


    @Override
    public int getOrder() {
        return 1;
    }
}
